import type { GenerateCodeParams, ComponentInfo } from '../types/index.js';
import { ComponentRegistry } from './ComponentRegistry.js';
import { TemplateEngine } from '../templates/TemplateEngine.js';

export class CodeGenerator {
  private componentRegistry: ComponentRegistry;
  private templateEngine: TemplateEngine;

  constructor() {
    this.componentRegistry = new ComponentRegistry();
    this.templateEngine = new TemplateEngine();
  }

  async generateCode(params: GenerateCodeParams): Promise<string> {
    const component = this.componentRegistry.getComponent(params.component);
    
    if (!component) {
      throw new Error(`Component not found: ${params.component}`);
    }

    const framework = params.framework || 'react';
    
    switch (framework) {
      case 'react':
        return this.generateReactCode(component, params);
      case 'vue':
        return this.generateVueCode(component, params);
      case 'angular':
        return this.generateAngularCode(component, params);
      case 'umi':
        return this.generateUmiCode(component, params);
      case 'umi-max':
        return this.generateUmiMaxCode(component, params);
      default:
        throw new Error(`Unsupported framework: ${framework}`);
    }
  }

  private generateReactCode(component: ComponentInfo, params: GenerateCodeParams): string {
    const { props = {}, includeImports = true, includeStyles = false, template } = params;
    
    let code = '';
    
    // 生成导入语句
    if (includeImports) {
      code += this.generateImports(component, 'react');
      code += '\n\n';
    }

    // 使用模板或生成基础组件代码
    if (template) {
      code += this.templateEngine.renderTemplate(template, {
        componentName: component.name,
        props,
        ...params
      });
    } else {
      code += this.generateBasicReactComponent(component, props);
    }

    // 添加样式
    if (includeStyles) {
      code += this.generateStyles(component, 'react');
    }

    return code;
  }

  private generateVueCode(component: ComponentInfo, params: GenerateCodeParams): string {
    const { props = {}, includeImports = true } = params;
    
    let code = '';
    
    if (includeImports) {
      code += `<script setup lang="ts">\n`;
      code += `import { ${component.name} } from 'ant-design-vue';\n`;
      code += `</script>\n\n`;
    }

    code += `<template>\n`;
    code += `  <${component.name}`;
    
    // 添加属性
    for (const [key, value] of Object.entries(props)) {
      if (typeof value === 'string') {
        code += ` ${key}="${value}"`;
      } else if (typeof value === 'boolean') {
        code += ` :${key}="${value}"`;
      } else {
        code += ` :${key}="${JSON.stringify(value)}"`;
      }
    }
    
    code += `>\n`;
    
    if (component.name === 'Button') {
      code += `    按钮文本\n`;
    }
    
    code += `  </${component.name}>\n`;
    code += `</template>`;

    return code;
  }

  private generateAngularCode(component: ComponentInfo, params: GenerateCodeParams): string {
    // Angular 实现（简化版）
    const { props = {} } = params;
    
    let code = `<!-- ${component.name} Component -->\n`;
    code += `<nz-${component.name.toLowerCase()}`;
    
    for (const [key, value] of Object.entries(props)) {
      if (typeof value === 'string') {
        code += ` ${key}="${value}"`;
      } else {
        code += ` [${key}]="${JSON.stringify(value)}"`;
      }
    }
    
    code += `>\n`;
    
    if (component.name === 'Button') {
      code += `  按钮文本\n`;
    }
    
    code += `</nz-${component.name.toLowerCase()}>`;

    return code;
  }

  private generateUmiCode(component: ComponentInfo, params: GenerateCodeParams): string {
    const { props = {}, includeImports = true, includeStyles = false, template } = params;
    
    let code = '';
    
    // 生成导入语句 - UmiJS 使用标准的 React + Ant Design
    if (includeImports) {
      code += `import React from 'react';\n`;
      code += this.generateImports(component, 'react');
      code += `\nimport { history } from 'umi';\n`;
      code += '\n';
    }

    // 使用模板或生成基础组件代码
    if (template) {
      code += this.templateEngine.renderTemplate(template, {
        componentName: component.name,
        props,
        framework: 'umi',
        ...params
      });
    } else {
      code += this.generateUmiPageComponent(component, props);
    }

    // 添加样式
    if (includeStyles) {
      code += this.generateStyles(component, 'umi');
    }

    return code;
  }

  private generateUmiMaxCode(component: ComponentInfo, params: GenerateCodeParams): string {
    const { props = {}, includeImports = true, includeStyles = false, template } = params;
    
    let code = '';
    
    // 生成导入语句 - Umi Max 支持更多高级特性
    if (includeImports) {
      code += `import React from 'react';\n`;
      code += this.generateImports(component, 'react');
      code += `\nimport { history, useModel, useRequest } from '@umijs/max';\n`;
      code += '\n';
    }

    // 使用模板或生成基础组件代码
    if (template) {
      code += this.templateEngine.renderTemplate(template, {
        componentName: component.name,
        props,
        framework: 'umi-max',
        ...params
      });
    } else {
      code += this.generateUmiMaxPageComponent(component, props);
    }

    // 添加样式
    if (includeStyles) {
      code += this.generateStyles(component, 'umi-max');
    }

    return code;
  }

  private generateUmiPageComponent(component: ComponentInfo, props: Record<string, any>): string {
    let code = `const IndexPage: React.FC = () => {\n`;
    
    // 添加 UmiJS 特有的 hooks
    code += `  // UmiJS 路由导航\n`;
    code += `  const handleNavigate = (path: string) => {\n`;
    code += `    history.push(path);\n`;
    code += `  };\n\n`;
    
    code += `  return (\n`;
    code += `    <div className="page-container">\n`;
    code += `      <h1>UmiJS 页面</h1>\n`;
    code += `      ${this.generateBasicReactComponent(component, props).split('\n').map(line => '      ' + line).join('\n')}\n`;
    code += `    </div>\n`;
    code += `  );\n`;
    code += `};\n\n`;
    code += `export default IndexPage;`;
    
    return code;
  }

  private generateUmiMaxPageComponent(component: ComponentInfo, props: Record<string, any>): string {
    let code = `const IndexPage: React.FC = () => {\n`;
    
    // 添加 Umi Max 特有的 hooks
    code += `  // Umi Max 数据管理\n`;
    code += `  const { initialState } = useModel('@@initialState');\n`;
    code += `  const { data, loading, error } = useRequest(async () => {\n`;
    code += `    // 这里可以调用 API\n`;
    code += `    return Promise.resolve({ message: 'Hello Umi Max!' });\n`;
    code += `  });\n\n`;
    
    code += `  // 路由导航\n`;
    code += `  const handleNavigate = (path: string) => {\n`;
    code += `    history.push(path);\n`;
    code += `  };\n\n`;
    
    code += `  if (loading) return <div>加载中...</div>;\n`;
    code += `  if (error) return <div>加载失败</div>;\n\n`;
    
    code += `  return (\n`;
    code += `    <div className="page-container">\n`;
    code += `      <h1>Umi Max 页面</h1>\n`;
    code += `      <p>用户信息: {initialState?.name}</p>\n`;
    code += `      <p>数据: {data?.message}</p>\n`;
    code += `      ${this.generateBasicReactComponent(component, props).split('\n').map(line => '      ' + line).join('\n')}\n`;
    code += `    </div>\n`;
    code += `  );\n`;
    code += `};\n\n`;
    code += `export default IndexPage;`;
    
    return code;
  }

  private generateBasicReactComponent(component: ComponentInfo, props: Record<string, any>): string {
    let code = `<${component.name}`;
    
    // 添加属性
    for (const [key, value] of Object.entries(props)) {
      if (typeof value === 'string') {
        code += `\n  ${key}="${value}"`;
      } else if (typeof value === 'boolean') {
        code += `\n  ${key}={${value}}`;
      } else if (typeof value === 'function') {
        code += `\n  ${key}={${value.toString()}}`;
      } else {
        code += `\n  ${key}={${JSON.stringify(value)}}`;
      }
    }
    
    // 特殊处理一些组件
    if (component.name === 'Button') {
      code += `>\n  ${props.children || '按钮文本'}\n</${component.name}>`;
    } else if (component.name === 'Table') {
      code += `\n/>`;
    } else if (component.name === 'Form') {
      code += `>\n  {/* 表单项 */}\n</${component.name}>`;
    } else {
      code += `\n/>`;
    }

    return code;
  }

  private generateImports(component: ComponentInfo, framework: string): string {
    if (framework === 'react' || framework === 'umi' || framework === 'umi-max') {
      if (component.imports && component.imports.length > 0) {
        return component.imports.join('\n');
      }
      return `import { ${component.name} } from 'antd';`;
    } else if (framework === 'vue') {
      return `import { ${component.name} } from 'ant-design-vue';`;
    } else if (framework === 'angular') {
      return `import { Nz${component.name}Module } from 'ng-zorro-antd/${component.name.toLowerCase()}';`;
    }
    return '';
  }

  private generateStyles(component: ComponentInfo, framework: string): string {
    if (framework === 'react' || framework === 'umi' || framework === 'umi-max') {
      return `\n\n// 样式文件\nconst styles = {\n  container: {\n    padding: '20px',\n  },\n};`;
    }
    return '';
  }

  generateComponentExample(componentName: string, exampleIndex = 0): string {
    const component = this.componentRegistry.getComponent(componentName);
    
    if (!component || !component.examples[exampleIndex]) {
      throw new Error(`Example not found for component: ${componentName}`);
    }

    const example = component.examples[exampleIndex];
    let code = '';
    
    // 添加导入语句
    if (component.imports) {
      code += component.imports.join('\n') + '\n\n';
    }

    // 添加示例代码
    code += `// ${example.title}\n`;
    code += `// ${example.description}\n\n`;
    code += example.code;

    return code;
  }

  generateFullComponent(componentName: string, props: Record<string, any> = {}): string {
    const component = this.componentRegistry.getComponent(componentName);
    
    if (!component) {
      throw new Error(`Component not found: ${componentName}`);
    }

    let code = '';
    
    // 添加导入
    code += `import React from 'react';\n`;
    if (component.imports) {
      code += component.imports.join('\n') + '\n';
    }
    code += '\n';

    // 生成组件
    code += `const MyComponent: React.FC = () => {\n`;
    
    // 添加事件处理函数（如果需要）
    if (componentName === 'Button' && !props.onClick) {
      code += `  const handleClick = () => {\n`;
      code += `    console.log('Button clicked!');\n`;
      code += `  };\n\n`;
      props.onClick = 'handleClick';
    }

    code += `  return (\n`;
    code += `    <div>\n`;
    code += `      ${this.generateBasicReactComponent(component, props).split('\n').map(line => '      ' + line).join('\n')}\n`;
    code += `    </div>\n`;
    code += `  );\n`;
    code += `};\n\n`;
    code += `export default MyComponent;`;

    return code;
  }
}